package com.tth.learn.addproperties.java;

import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * @Author tth
 * @Date 2022/12/27 15:00
 */
public class RandomAccessFileTest {


    @Test
    public void test1() {
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            // 1.造流
            raf1 = new RandomAccessFile(new File("img.png"), "r");
            raf2 = new RandomAccessFile(new File("image1.png"), "rw");

            // 2.复制
            byte[] buffer = new byte[1024];
            int len;
            while ((len = raf1.read(buffer)) != -1) {
                raf2.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭流
            if (null != raf2) {
                try {
                    raf2.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != raf1) {
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void test2() {
        RandomAccessFile raf = null;
        try {
            // 1.造流
            raf = new RandomAccessFile("hello.txt", "rw");

            // 2.插入
            // 2.1保存指针3后边的数据到StringBuilder中
            raf.seek(3);
            StringBuilder sb = new StringBuilder((int)new File("hello.txt").length());
            byte[] buff = new byte[10];
            int len;
            while ((len = raf.read(buff)) != -1) {
                sb.append(new String(buff, 0, len));
            }
            // 2.2调回指针，在3的位置后进行插入
            raf.seek(3);
            raf.write("xyz".getBytes());
            // 2.3将StringBuilder中的数据写入到文件
            raf.write(sb.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭流
            if (null != raf) {
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
